﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Twitterizer;
using Social;

namespace Social.Twitter
{
   public class TwitterWrapper
    {

       private static string ConsumerKey
       {
           get { return ConfigurationManager.AppSettings["TwitterConsumerKey"]; }
       }

       private static string ConsumerSecret
       {
           get { return ConfigurationManager.AppSettings["TwitterConsumerSecret"]; }
       }

       private const string FollowerIdsUrlFromat = "http://api.twitter.com/1/followers/ids.json?user_id={0}";
       private const string FollowerUrlFromat = "http://api.twitter.com/1/statuses/followers.json?user_id={0}&cursor=";


       public static string GetAuthUrl(string callbackUrl)
       {
           var rToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, callbackUrl);
           var url = OAuthUtility.BuildAuthorizationUri(rToken.Token);
           return url.AbsoluteUri;
       }

       public static OAuthTokenResponse GetTokenFromRequest()
       {
           try
           {
               var res = Twitterizer.OAuthUtility.GetAccessTokenDuringCallback(ConfigurationManager.AppSettings["TwitterConsumerKey"], ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
               return res;
           }
           catch (Exception ex)
           {
               return new OAuthTokenResponse { Token = string.Empty };

           }
       }


       public OAuthTokens Token { get; set; }
       public TwitterWrapper(string token, string secret)
       {
           Token = new OAuthTokens { AccessToken = token, AccessTokenSecret = secret, ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret };
       }

       
       
       public ContentServiceResponse<string> Post(string text)
       {
           var response = new ContentServiceResponse<string>();
           try
           {
			   response.Content = Twitterizer.TwitterStatus.Update(Token, text).ResponseObject.Id.ToString(); ;
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }

           return response;


       }

       public ContentServiceResponse<TwUser> GetUser(decimal id)
       {
           var response = new ContentServiceResponse<TwUser>();

           try
           {
               var res = Twitterizer.TwitterUser.Show(Token, id).ResponseObject;
               response.Content = new TwUser(res);
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }

           return response;
       }

	   public ContentServiceResponse<TwitterUserCollection> GetFolowers(decimal userId)
	   {
		   var response = new ContentServiceResponse<TwitterUserCollection>();

		   try
		   {

			   response.Content = Twitterizer.TwitterFriendship.Followers(Token, new FollowersOptions() { UserId = userId }).ResponseObject;
			   response.SetSuccess();
		   }
		   catch (Exception ex)
		   {
			   response.SetException(ex);
		   }

		   return response;

	   }

	   public ContentServiceResponse<TwitterUserCollection> GetFriends(decimal userId)
	   {
		   var response = new ContentServiceResponse<TwitterUserCollection>();

		   try
		   {
			   response.Content = Twitterizer.TwitterFriendship.Friends(Token, new FriendsOptions() { UserId = userId }).ResponseObject;
			   response.SetSuccess();
		   }
		   catch (Exception ex)
		   {
			   response.SetException(ex);
		   }

		   return response;

	   }

       internal ContentServiceResponse<TwitterStatusCollection> GetRetweets(string statusID)
       {
           var response = new ContentServiceResponse<TwitterStatusCollection>();

           try
           {
               var options = new RetweetsOptions { Count = 200 };
               response.Content = Twitterizer.TwitterStatus.Retweets(Token, decimal.Parse(statusID), options).ResponseObject;
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }
           return response;
       }


       internal ContentServiceResponse<TwitterStatusCollection> GetReplies()
       {
           return GetReplies(null);
       }
	   internal ContentServiceResponse<TwitterStatusCollection> GetReplies(string fromStatusID)
       {
           var response = new ContentServiceResponse<TwitterStatusCollection>();


           try
           {
               var options = new Twitterizer.TimelineOptions { IncludeRetweets = false };
               decimal since = new decimal();
               if (!string.IsNullOrEmpty(fromStatusID) && decimal.TryParse(fromStatusID, out since))
                   options.SinceStatusId = since;

               response.Content = Twitterizer.TwitterTimeline.Mentions(Token, options).ResponseObject;
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }
           return response;
       }

       /// <summary>
       /// Gets the replies for a specified twitter status
       /// </summary>
       /// <param name="statusID">The status for which to get the replies</param>
       /// <param name="fromStatusID">The ID of the last comment to retrieve from. If this argument is null the status ID itself will be used</param>
       /// <returns></returns>
       internal ContentServiceResponse<List<TwitterStatus>> GetRepliesForStatus(string statusID, string fromStatusID)
       {
           decimal id = new decimal();
           if (string.IsNullOrEmpty(statusID) || !decimal.TryParse(statusID, out id))
               return new ContentServiceResponse<List<TwitterStatus>> { ResultOption = ServiceResultOptions.IncorrectParameters };

           //if there is no fromStatusID specified, use the statusId itself.
           if (string.IsNullOrEmpty(fromStatusID))
               fromStatusID = statusID;

           //get all replies for this user
           var response = GetReplies(fromStatusID);
           if (response.ResultOption != ServiceResultOptions.Success)
               return new ContentServiceResponse<List<TwitterStatus>> { ResultOption = response.ResultOption, Message = response.Message };
           
           //filter the replies that are not for the specified statusID
           var filtered = response.Content.Where(t => (t.InReplyToStatusId == id));
           return new ContentServiceResponse<List<TwitterStatus>> { Content = filtered.ToList(), ResultOption = response.ResultOption };//response.Content = filtered.ToList();
       }

       public static ContentServiceResponse<List<long>> GetFollowerIds(decimal userID)
       {
           var response = new ContentServiceResponse<List<long>>();
           try
           {
               var url = string.Format(FollowerIdsUrlFromat, userID);
               var result = WebReq.GetWebResponse(url);
               response.Content = JSON.DeserializeJSON<List<long>>(result);
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }
           
           return response;
       }

       //public  ContentServiceResponse<List<TwitterUser>> GetFollowers()
       //{
       //    return GetFollowers(-1);
       //}
       public ContentServiceResponse<List<TwitterUser>> GetFollowers(decimal Id)
       {
           var response = new ContentServiceResponse<List<TwitterUser>>();
          
           try
           {
               var options = new FollowersOptions ();
               if (Id != -1)
                   options.UserId = Id;
              
			   var result = Twitterizer.TwitterFriendship.Followers(Token, options);
               var followers= result.ResponseObject;
               response.Content = new List<TwitterUser>();

               while((followers != null) && (followers.Count > 0))  
               {
                    foreach (TwitterUser follower in followers)
	                {
                        response.Content.Add(follower);
	                }
                   //if there are no more pages to retrieve, stop the loop
                    if (followers.NextCursor == 0)
                        break;
                   //get the next page
                    followers = followers.NextPage().ResponseObject;
               }
             
               response.SetSuccess();
           }
           catch (Exception ex)
           {
               response.SetException(ex);
           }

           return response;
       }

       public ContentServiceResponse<List<TwitterUser>> GetFollowers(string ID)
       {
            decimal uid;
            if (decimal.TryParse(ID, out uid))
                return GetFollowers(uid);
            else return GetFollowers(-1);
       }
    
       //public ContentServiceResponse<TwitterUserCollection> GetFollowers(decimal ID)
       //{
       //    var response = new ContentServiceResponse<TwitterUserCollection>();

       //    try
       //    {
       //            var options = new FollowersOptions { UserId = ID };
       //            response.Content = Twitterizer.TwitterFriendship.Followers(options);
       //            response.SetSuccess();
       //    }
       //    catch (Exception ex)
       //    {
       //        response.SetException(ex);
       //    }

       //    return response;
       //}

       public class TwUser : TwitterUser
       {
           public TwUser() { }
           public TwUser(TwitterUser tUser) 
           { 
            this.CreatedDate = tUser.CreatedDate;
            this.Description = tUser.Description;
            this.DoesReceiveNotifications = tUser.DoesReceiveNotifications;
            this.Id = tUser.Id;
            //this.IsEmpty= tUser.IsEmpty;
            this.IsFollowedBy= tUser.IsFollowedBy;
            this.IsFollowing= tUser.IsFollowing;
            this.IsGeoEnabled= tUser.IsGeoEnabled;
            this.IsProfileBackgroundTiled = tUser.IsProfileBackgroundTiled;
            this.IsProtected= tUser.IsProtected;
            this.Language= tUser.Language;
            this.Location = tUser.Location;
            this.Name = tUser.Name;
            this.NumberOfFavorites= tUser.NumberOfFavorites;
            this.NumberOfFollowers = tUser.NumberOfFollowers;
            this.NumberOfFriends = tUser.NumberOfFriends;
            this.NumberOfStatuses = tUser.NumberOfStatuses;
            //this.ProfileBackgroundColor = tUser.ProfileBackgroundColor;
            this.ProfileBackgroundColorString= tUser.ProfileBackgroundColorString;
            this.ProfileBackgroundImageLocation = tUser.ProfileBackgroundImageLocation;
            this.ProfileImageLocation = tUser.ProfileImageLocation;
            //this.ProfileLinkColor= tUser.ProfileLinkColor;
            this.ProfileLinkColorString= tUser.ProfileLinkColorString;
            //this.ProfileSidebarBorderColor
            //this.ProfileSidebarBorderColorString= 
            //this.ProfileTextColor= tUser.IsContributorsEnabled;
            //this.ProfileTextColorString= tUser.IsContributorsEnabled;
            //this.RateLimiting = tUser.IsContributorsEnabled;
            //this.RequestStatus= tUser.IsContributorsEnabled;
            this.ScreenName= tUser.ScreenName;
            //this.Status = tUser.IsContributorsEnabled;
            this.TimeZone = tUser.TimeZone;
            this.TimeZoneOffset = tUser.TimeZoneOffset;
            this.Website = tUser.Website;
            
           }

           public static TwUser Parse(TwitterUser tUser)
           {
               return new TwUser(tUser);
           }
       }

       
    }
}
